<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>resolve数据缓存</title>
</head>

<body>

</body>
<script src="ajax.js"></script>
<script>
    function query(name) {
        const cache = query.cache || (query.cache = new Map())
        if(cache.has(name)){
            console.log("走缓存了")
            return Promise.resolve(cache.get(name))
        }
        return ajax(`http://localhost:7001/js/userInfo?name=${name}`).then(
            user => {
                console.log("访问后端了")
                cache.set(name,user)
                
                return user //与下面新生成的promise等价
                // return new Promise(resolve=>{
                //     resolve(user)
                // })
            }
        )
    }

    query("test").then(
        user => console.log(user)
    )

    // 走缓存测试
    setTimeout(() => {
        query("test").then( user => console.log(user))
    }, 3000)

    // promise.resolve 类似封装：
    Promise.test = function (value) {
        return new Promise(resolve=>{
            resolve(value)
        })
    }
    Promise.test("test-ok").then(ok=>console.log(ok))
    Promise.resolve("promise-ok").then(ok=>console.log(ok))


    // // 函数本身也是一个对象   cache缓存
    // function test(){}
    // test.site = "http://"
    // console.dir(test)



</script>

</html>